// import { BasicLayout, BlankLayout, PageView, RouteView } from '@/layouts'
import store from '@/store'
import Layout from '@/layout'
import path from 'path'
// 前端路由表 = 基础定义 + 动态组件
/**
 * Note: sub-menu only appear when route children.length >= 1
 * Detail see: https://panjiachen.github.io/vue-element-admin-site/guide/essentials/router-and-nav.html
 *
 * hidden: true                   if set true, item will not show in the sidebar(default is false)
 * alwaysShow: true               if set true, will always show the root menu
 *                                if not set alwaysShow, when item has more than one children route,
 *                                it will becomes nested mode, otherwise not show the root menu
 * redirect: noRedirect           if set noRedirect will no redirect in the breadcrumb
 * name:'router-name'             the name is used by <keep-alive> (must set!!!)
 * meta : {
    roles: ['admin','editor']    control the page roles (you can set multiple roles)
    title: 'title'               the name show in sidebar and breadcrumb (recommend set)
    icon: 'svg-name'/'el-icon-x' the icon show in the sidebar
    noCache: true                if set true, the page will no be cached(default is false)
    affix: true                  if set true, the tag will affix in the tags-view
    breadcrumb: false            if set false, the item will hidden in breadcrumb(default is true)
    activeMenu: '/example/list'  if set path, the sidebar will highlight the path you set
  }
 */
const asyncRoute = {
  'ENT_C_MAIN':{
    path: '/main',
    component: ()=>import('@/layout'),
    redirect: '/main',
    children: [{
      path: '',
      name: 'Main',
      component: () => import('@/views/dashboard/index'),
      meta: { title: '主页', icon: 'el-icon-s-home',affix:true }
    }]
  },
  'ENT_MCH':{
    entId: "ENT_MCH",
    path: '/mch',
    component: ()=>import('@/layout'),
    redirect: '',
    name: 'Mch',
    alwaysShow:true,
    meta: { title: '商户管理', icon: 'el-icon-shopping-cart-1' },
    children: []
  },
  'ENT_MCH_INFO':{
    entId: "ENT_MCH_INFO",
    path: 'info',
    name: 'Info',
    component: () => import('@/views/mch/MchList.vue'),
    meta: { title: '商户列表', icon: 'el-icon-tickets' }
  },
  'ENT_MCH_APP':{
    entId: "ENT_MCH_APP",
    path: 'apps',
    name: 'Apps',
    component: () => import('@/views/mchApp/List.vue'),
    meta: { title: '应用列表', icon: 'el-icon-shopping-bag-1' }
  },
  'ENT_ISV':{
    entId: "ENT_ISV",
    path: '/isv',
    component: ()=>import('@/layout'),
    redirect: '',
    name: 'Isv',
    meta: { title: '服务商管理', icon: 'el-icon-connection' },
    alwaysShow:true,
    children: []
  },
  'ENT_ISV_INFO':{
    entId: "ENT_ISV_INFO",
    path: 'info',
    name: 'IsvList',
    component: () => import('@/views/isv/IsvList.vue'),
    meta: { title: '服务商列表', icon: 'el-icon-notebook-2' }
  },
  'ENT_ORDER':{
    entId: "ENT_ORDER",
    path: '/order',
    component: ()=>import('@/layout'),
    redirect: '',
    name: 'Order',
    alwaysShow:true,
    meta: { title: '订单管理', icon: 'el-icon-wallet' },
    children: []
  },
  'ENT_PAY_ORDER':{
    entId: "ENT_PAY_ORDER",
    path: 'pay',
    name: 'Pay',
    component: () => import('@/views/order/pay/PayOrderList.vue'),
    meta: { title: '支付订单', icon: 'el-icon-shopping-bag-1' }
  },
  'ENT_REFUND_ORDER':{
    entId: "ENT_REFUND_ORDER",
    path: 'refund',
    name: 'Refund',
    component: () => import('@/views/order/refund/RefundOrderList.vue'),
    meta: { title: '退款订单', icon: 'el-icon-shopping-bag-2' }
  },
  'ENT_TRANSFER_ORDER':{
    entId: "ENT_TRANSFER_ORDER",
    path: 'transfer',
    name: 'Transfer',
    component: () => import('@/views/order/transfer/TransferOrderList.vue'),
    meta: { title: '转账订单', icon: 'el-icon-sold-out' }
  },
  'ENT_MCH_NOTIFY':{
    entId: "ENT_MCH_NOTIFY",
    path: 'notify',
    name: 'Notify',
    component: () => import('@/views/order/notify/NotifyList.vue'),
    meta: { title: '商户通知', icon: 'el-icon-bell' }
  },
  'ENT_PC':{
    entId: "ENT_PC",
    path: '/pc',
    component: ()=>import('@/layout'),
    redirect: '',
    name: 'Pc',
    alwaysShow:true,
    meta: { title: '支付管理', icon: 'el-icon-cpu' },
    children: []
  },
  'ENT_PC_IF_DEFINE':{
    entId: "ENT_PC_IF_DEFINE",
    path: 'ifdefines',
    name: 'Ifdefines',
    component: () => import('@/views/payconfig/payIfDefine/List.vue'),
    meta: { title: '支付接口', icon: 'el-icon-link' }
  },
  'ENT_PC_WAY':{
    entId: "ENT_PC_WAY",
    path: 'payways',
    name: 'Payways',
    component: () => import('@/views/payconfig/payWay/List.vue'),
    meta: { title: '支付方式', icon: 'el-icon-takeaway-box' }
  },
  'ENT_SYS_CONFIG':{
    entId: "ENT_SYS_CONFIG",
    path: '/sys',
    component: ()=>import('@/layout'),
    redirect: '',
    name: 'Sys',
    alwaysShow:true,
    meta: { title: '系统管理', icon: 'el-icon-setting' },
    children: []
  },
  'ENT_UR':{
    entId: "ENT_UR",
    path: 'user',
    name: 'User',
    alwaysShow:true,
    meta: { title: '用户角色管理', icon: 'el-icon-bangzhu' },
    component: () => import('@/views/sysuser/index.vue'),
    children: []
  },
  'ENT_UR_USER':{
    entId: "ENT_UR_USER",
    path: 'admin',
    name: 'Admin',
    component: () => import('@/views/sysuser/SysUserPage.vue'),
    meta: { title: '操作员管理', icon: 'el-icon-user' }
  },
  'ENT_UR_ROLE':{
    entId: "ENT_UR_ROLE",
    path: 'roles',
    name: 'Roles',
    component: () => import('@/views/role/RolePage.vue'),
    meta: { title: '角色管理', icon: 'el-icon-film' }
  },
  'ENT_UR_ROLE_ENT':{
    entId: "ENT_UR_ROLE_ENT",
    path: 'ents',
    name: 'Ents',
    component: () => import('@/views/ent/EntPage.vue'),
    meta: { title: '权限管理', icon: 'el-icon-open' }
  },
  'ENT_SYS_CONFIG_INFO':{
    entId: "ENT_SYS_CONFIG_INFO",
    path: 'config',
    name: 'Config',
    component: () => import('@/views/sys/config/SysConfig.vue'),
    meta: { title: '系统配置', icon: 'el-icon-coordinate' }
  },
  'ENT_SYS_LOG':{
    entId: "ENT_SYS_LOG",
    path: 'log',
    name: 'Log',
    component: () => import('@/views/sys/log/SysLog.vue'),
    meta: { title: '系统日志', icon: 'el-icon-coin' }
  }
} 
// 根级菜单
const rootRouter = {
    path: '/',
    component: ()=>import('@/layout'),
    redirect: redirectFunc,
  }

// 动态跳转路径 func
function redirectFunc () {
  let mainPageUri = ''
    store.state.user.allMenuRouteTree.forEach(item => {
    if (item.entId === 'ENT_C_MAIN') { // 当前用户是否拥有主页权限， 如果有直接跳转到该路径
      mainPageUri = '/main'
      return false
    }
  })

  if (mainPageUri) {
    return mainPageUri
  }

  return getOneUri(store.state.user.allMenuRouteTree)
}
// 获取到第一个uri (递归查找)
let redirect = ''
let  pathUrl =''
function getOneUri (item) {
  for (let i = 0; i < item.length; i++) {
    if (item[i].entId && item[i].children) {
       pathUrl = asyncRoute[item[i].entId].path
       redirect= path.resolve(redirect, pathUrl)
       getOneUri(item[i].children)
    }else{
      pathUrl = asyncRoute[item[i].entId].path
      redirect = path.resolve(redirect, pathUrl)
      return  redirect
    }
  }
  return redirect
}

// 前端未找到页面路由
const notFoundRouter = { path: '*', redirect: '/404', hidden: true }

/**
 * 动态生成菜单
 * @param token
 * @returns {Promise<Router>}
 */
 export const generatorDynamicRouter = () => {
    return new Promise((resolve, reject) => {
        // 根据树状结构生成路由格式
        let dynamicRouter = []
        dynamicRouter.push(rootRouter)
        const  getRouter = generator(store.state.user.allMenuRouteTree)
        dynamicRouter = dynamicRouter.concat(getRouter)
      // 构建完整路由
       dynamicRouter.push(notFoundRouter)
      resolve(dynamicRouter)
    })
}


/**
 * 格式化树形结构数据 生成 vue-router 层级路由表
 *
 * @param routerMap
 * @returns {*}
 */
 export const generator = (allMenuRouteTreeArray) => {
  let menuResult = []

  // 遍历map
  allMenuRouteTreeArray.map(item => {
    // 找不到菜单id
    if (!asyncRoute.hasOwnProperty(item.entId)) {
      return
    }
    const currentRouter = asyncRoute[item.entId]
    // currentRouter.component = asyncRoute[item.entId].component

    // 是否有子菜单，并递归处理
    if (item.children && item.children.length > 0) {
      // Recursion
      currentRouter.children = generator(item.children)
      
    }
    menuResult.push(currentRouter)
  })

  return menuResult
}
